﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Windows;
using System.Windows.Input;
using TodoListApp.Commands;
using TodoListApp.Models;

namespace TodoListApp.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        //private string _todoContent = string.Empty;
        //public string TodoContent
        //{
        //    get => _todoContent;
        //    set
        //    {
        //        _todoContent = value;
        //    }
        //}

        private string _todoInput = string.Empty;
        private ObservableCollection<TodoItem> _todoItems = new();

        //private readonly string _dataRepository = Path.Combine(
        //    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        //    "TodoListApp",
        //    "todos.json");
        private readonly string _dataRepository = Path.Combine(Environment.CurrentDirectory, "todos.json");

        public string TodoInput
        {
            get => _todoInput;
            set
            {
                _todoInput = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<TodoItem> TodoItems
        {
            get => _todoItems;
            set
            {
                _todoItems = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public ICommand AddCommand { get; }
        public ICommand DeleteCommand { get; }

        public MainViewModel()
        {
            //AddCommand = new RelayCommand(OnClick);
            AddCommand = new RelayCommand(AddTodoItem, CanAddTodoItem);
            DeleteCommand = new RelayCommand(DeleteSlectedItems, CanDeleteItems);

            LoadTodos();
        }

        private void OnClick()
        {
            //TodoContent = "按钮被点击了！（MVVM方式）";
            //MessageBox.Show(TodoContent, "提示");
        }

        private void AddTodoItem(object parameter)
        {
            TodoItems.Add(new TodoItem
            {
                TodoContent = TodoInput,
            });
            AddTodo(TodoInput);
            TodoInput = string.Empty;
        }

        private bool CanAddTodoItem(object parameter)
        {
            return !string.IsNullOrWhiteSpace(TodoInput);
        }

        private void DeleteSlectedItems(object obj)
        {
            try
            {
                var selectedItems = TodoItems.Where(item => item.IsSelected).ToList();
                
                foreach (var item in selectedItems)
                {
                    TodoItems.Remove(item);
                }

                SaveTodos();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据失败: {ex.Message}", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool CanDeleteItems(object obj)
        {
            return TodoItems.Any(item => item.IsSelected);
        }

        private void LoadTodos()
        {
            try
            {
                if (File.Exists(_dataRepository))
                {
                    string data = File.ReadAllText(_dataRepository);
                    if (string.IsNullOrEmpty(data))
                    {
                        return;
                    }

                    var items = JsonSerializer.Deserialize<List<TodoItem>>(data);
                    if (items == null || items.Count == 0)
                    {
                        return;
                    }

                    TodoItems = new ObservableCollection<TodoItem>(items);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SaveTodos()
        {
            try
            {
                var dir = Path.GetDirectoryName(_dataRepository);
                if (!Directory.Exists(dir))
                {
                    return;
                }

                Directory.CreateDirectory(dir);
                var data = JsonSerializer.Serialize(TodoItems.ToList(), new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_dataRepository, data);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void AddTodo(string todo)
        {
            try
            {
                if (!File.Exists(_dataRepository))
                {
                    File.Create(_dataRepository);
                    File.WriteAllText(_dataRepository, GetJsonString(todo));
                    return;
                }

                var data = File.ReadAllText(_dataRepository);
                if (data.Length == 0)
                {
                    File.WriteAllText(_dataRepository, GetJsonString(todo));
                    return;
                }

                var rootNode = JsonNode.Parse(data);
                if (rootNode == null)
                {
                    return;
                }

                var jsonArray = rootNode.AsArray();
                jsonArray.Add(new JsonObject {
                    ["todo_content"] = JsonValue.Create(todo)
                });
                var todoString = jsonArray.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_dataRepository, todoString);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private string GetJsonString(string todo)
        {
            var jsonTodos = new JsonArray
            {
                new JsonObject
                {
                    ["todo_content"] = JsonValue.Create(todo)
                }
            };
            return jsonTodos.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
        }

        private void whatever()
        {
            var data = File.ReadAllText(_dataRepository);
            if (data == string.Empty)
            {
                MessageBox.Show($"保存数据失败,数据文件内容为空", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var rootNode = JsonNode.Parse(data);
            if (rootNode == null)
            {
                MessageBox.Show($"保存数据失败,数据解析失败", "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var todosArray = rootNode.AsArray();
            foreach (var todo in todosArray)
            {
                if (todo != null && todo["todo_content"]?.GetValue<string>() == "")
                {
                    todosArray.Remove(todo);
                    break;
                }
            }

            File.WriteAllText(_dataRepository, todosArray.ToJsonString(new JsonSerializerOptions
            {
                WriteIndented = true,
            }));
        }
    }
}
